import {defineStore} from 'pinia';
import {v4 as uuidv4} from 'uuid';
import {getNodeTypeConfig} from '../config/nodeTypes';

export interface NodeData {
    id: string;
    type: string;
    label: string;
    position: { x: number; y: number };
    properties: Record<string, any>;
    inputs: Array<{ id: string; name: string; type: string }>;
    outputs: Array<{ id: string; name: string; type: string }>;
}

export interface ConnectionData {
    id: string;
    sourceNodeId: string;
    sourcePortId: string;
    targetNodeId: string;
    targetPortId: string;
}

export interface WorkflowData {
    id: string;
    name: string;
    nodes: NodeData[];
    connections: ConnectionData[];
    createdAt: Date;
    updatedAt: Date;
}

export interface WorkflowState {
    workflows: WorkflowData[];
    currentWorkflowId: string | null;
    selectedNodeId: string | null;
    selectedConnectionId: string | null;
    highlightedNodeIds: string[];
    highlightedConnectionIds: string[];
}

export const useWorkflowStore = defineStore('workflow', {
    state: (): WorkflowState => ({
        workflows: [],
        currentWorkflowId: null,
        selectedNodeId: null,
        selectedConnectionId: null,
        highlightedNodeIds: [],
        highlightedConnectionIds: []
    }),

    getters: {
        currentWorkflow: (state) => {
            if (!state.currentWorkflowId) return null;
            return state.workflows.find(wf => wf.id === state.currentWorkflowId);
        }
    },

    actions: {
        // 创建新工作流
        createWorkflow(name: string) {
            const id = uuidv4();
            this.workflows.push({
                createdAt: new Date(), updatedAt: new Date(),
                id,
                name,
                nodes: [],
                connections: []
            });
            this.currentWorkflowId = id;
            return id;
        },

        // 加载工作流
        loadWorkflow(id: string) {
            const workflow = this.workflows.find(wf => wf.id === id);
            if (workflow) {
                this.currentWorkflowId = id;
                this.clearSelection();
            }
        },

        // 重命名工作流
        renameWorkflow(id: string, newName: string) {
            const workflow = this.workflows.find(wf => wf.id === id);
            if (workflow) {
                workflow.name = newName;
            }
        },

        // 删除工作流
        deleteWorkflow(id: string) {
            const index = this.workflows.findIndex(wf => wf.id === id);
            if (index !== -1) {
                this.workflows.splice(index, 1);
                if (this.currentWorkflowId === id) {
                    this.currentWorkflowId = this.workflows.length > 0 ? this.workflows[0].id : null;
                }
            }
        },

        // 选择节点
        selectNode(nodeId: string) {
            this.selectedNodeId = nodeId;
            this.selectedConnectionId = null;
        },

        // 选择连接
        selectConnection(connectionId: string) {
            this.selectedConnectionId = connectionId;
            this.selectedNodeId = null; // 清除节点选择
        },

        // 删除连接
        deleteConnection(connectionId: string) {
            if (!this.currentWorkflow) return;

            this.currentWorkflow.connections = this.currentWorkflow.connections.filter(
                conn => conn.id !== connectionId
            );

            // 清除选择
            if (this.selectedConnectionId === connectionId) {
                this.selectedConnectionId = null;
            }
        },

        // 清除选择
        clearSelection() {
            this.selectedNodeId = null;
            this.selectedConnectionId = null;
        },

        // 添加节点
        addNode(type: string, label: string, x: number, y: number): string {
            if (!this.currentWorkflow) return '';

            // 获取节点类型配置
            const nodeTypeConfig = getNodeTypeConfig(type);
            if (!nodeTypeConfig) return '';

            // 创建新节点
            const nodeId = `node-${Date.now()}-${Math.floor(Math.random() * 1000)}`;
            const newNode: NodeData = {
                id: nodeId,
                type: type,
                label: label,
                position: {x, y},
                properties: {},
                inputs: nodeTypeConfig.ports?.inputs || [],
                outputs: nodeTypeConfig.ports?.outputs || []
            };

            // 初始化默认属性
            if (nodeTypeConfig.properties) {
                Object.entries(nodeTypeConfig.properties).forEach(([key, config]) => {
                    if ('default' in config) {
                        newNode.properties[key] = config.default;
                    }
                });
            }

            this.currentWorkflow.nodes.push(newNode);
            this.selectedNodeId = nodeId;

            return nodeId;
        },

        // 更新节点位置
        updateNodePosition(nodeId: string, position: { x: number; y: number }) {
            if (!this.currentWorkflow) return;

            const node = this.currentWorkflow.nodes.find(n => n.id === nodeId);
            if (node) {
                node.position = position;
            }
        },

        // 更新节点标签
        updateNodeLabel(nodeId: string, label: string) {
            if (!this.currentWorkflow) return;

            const node = this.currentWorkflow.nodes.find(n => n.id === nodeId);
            if (node) {
                node.label = label;
            }
        },

        // 更新节点属性
        updateNodeProperties(nodeId:string, properties: Record<string, any>) {
            const workflow = this.currentWorkflow;
            if (!workflow) return;

            const node = workflow.nodes.find(n => n.id === nodeId);
            if (node) {
                node.properties = {...properties};
            }
        },

        // 删除节点
        deleteNode(nodeId: string) {
            if (!this.currentWorkflow) return;

            // 先删除与该节点相关的所有连接
            this.currentWorkflow.connections = this.currentWorkflow.connections.filter(
                conn => conn.sourceNodeId !== nodeId && conn.targetNodeId !== nodeId
            );

            // 删除节点
            this.currentWorkflow.nodes = this.currentWorkflow.nodes.filter(
                node => node.id !== nodeId
            );

            // 如果删除的是当前选中的节点，清除选择
            if (this.selectedNodeId === nodeId) {
                this.selectedNodeId = null;
            }
        },

        // 复制节点
        duplicateNode(nodeId: string, newPosition: { x: number, y: number }) {
            if (!this.currentWorkflow) return;

            const sourceNode = this.currentWorkflow.nodes.find(node => node.id === nodeId);
            if (!sourceNode) return;

            // 创建新节点，复制原节点的属性
            const newNode = {
                ...JSON.parse(JSON.stringify(sourceNode)), // 深拷贝
                id: 'node_' + Date.now(), // 生成新的唯一ID
                position: newPosition,
                label: sourceNode.label + ' (复制)'
            };

            // 添加到工作流
            this.currentWorkflow.nodes.push(newNode);

            // 选中新节点
            this.selectNode(newNode.id);

            return newNode.id;
        },

        // 添加连接
        addConnection(sourceNodeId: string, sourcePortId: string, targetNodeId: string, targetPortId: string) {
            if (!this.currentWorkflow) return null;

            // 检查是否已存在相同的连接
            const existingConnection = this.currentWorkflow.connections.find(
                conn => conn.sourceNodeId === sourceNodeId &&
                    conn.sourcePortId === sourcePortId &&
                    conn.targetNodeId === targetNodeId &&
                    conn.targetPortId === targetPortId
            );

            if (existingConnection) {
                return null;
            }

            // 创建新连接
            const connectionId = `conn-${Date.now()}-${Math.floor(Math.random() * 1000)}`;
            const newConnection = {
                id: connectionId,
                sourceNodeId,
                sourcePortId,
                targetNodeId,
                targetPortId
            };

            this.currentWorkflow.connections.push(newConnection);
            this.selectedConnectionId = connectionId;

            return connectionId;
        },

        // 删除连接
        removeConnection(connectionId: string) {
            if (!this.currentWorkflow) return;

            this.currentWorkflow.connections = this.currentWorkflow.connections.filter(
                conn => conn.id !== connectionId
            );

            if (this.selectedConnectionId === connectionId) {
                this.selectedConnectionId = null;
            }
        },

        // 高亮节点相关的连接
        highlightNodeConnections(nodeId: string) {
            if (!this.currentWorkflow) return;

            // 查找与该节点相关的所有连接
            const relatedConnections = this.currentWorkflow.connections.filter(
                conn => conn.sourceNodeId === nodeId || conn.targetNodeId === nodeId
            );

            // 设置高亮连接ID
            this.highlightedConnectionIds = relatedConnections.map(conn => conn.id);
        }
    }
});